package com.basker.pisces.context;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType;

import com.basker.pisces.cache.ICache;
import com.basker.pisces.cache.ICache.ValueWrapper;
import com.basker.pisces.cache.ICacheManager;

/**
 * {@link ILoginContextManager}的抽象实现，提供{@link ICache}作为{@link LoginContext}的容器。子类继承的时候，需要明确LoginContext的类型，必要时可以给其加上缓存注解
 *
 * @param <T>
 * @author hangwen
 */
public abstract class AbstractLoginContextManager<T extends LoginContext>
        implements InitializingBean, ILoginContextManager<T> {

    @Autowired
    private ICacheManager cacheManager;

    private ICache<String, T> cache;

    @Override
    public final void afterPropertiesSet() throws Exception {
        @SuppressWarnings("unchecked")
        Class<T> loginContextType = (Class<T>) ResolvableType.forType(this.getClass())
                .as(AbstractLoginContextManager.class).resolveGeneric(0);
        this.cache = this.cacheManager.getCache(loginContextType);
    }

    @Override
    public T get(Token token) {
        ValueWrapper<T> valueWrapper = cache.get(token.getTokenId());
        return valueWrapper.get();
    }

    @Override
    public void put(Token token, T loginContext) {
        this.cache.put(token.getTokenId(), loginContext);
    }

    @Override
    public void remove(Token token) {
        T lcx = this.get(token);
        if (lcx != null) {
            this.cache.remove(token.getTokenId());
        }
    }

}
